<template>
  <div class="related-order-box">
    <el-select
      v-select-scroll
      v-model="relatedIds"
      :remote-method="emojiList"
      :collapse-tags="false"
      filterable
      multiple
      remote
      clearable
      reserve-keyword
      popper-class="related-order-item global-select-down"
      placeholder="请输入关键词搜索"
      @change="formatOption"
      @visible-change="isShowSelect">
      <el-option
        v-for="item in emojiOptions"
        :key="item.id"
        :label="item.name"
        :value="item.id" />
    </el-select>
  </div>
</template>
<script>
import { getRelatedList } from '@/api/mengli';

export default {
  name: 'RelateEmoji',
  props: {
    ids: {
      type: Array,
      default: () => []
    },
    options: {
      type: Array,
      default: () => []
    },
    reservedField: {
      type: [Array, String],
      default: () => ['id', 'name']
    }
  },

  data() {
    return {
      relatedIds: [],
      emojiOptions: [], // 关联表情包
      optionArr: [],
      cacheLen: 0,
      currentPage: null,
      emojiTotal: null,
      emojioName: ''
    };
  },

  watch: {
    ids: {
      handler(newV) {
        this.relatedIds = newV;
        this.cacheLen = this.relatedIds.length;
      },
      immediate: true
    },
    options: {
      handler(newV) {
        const newArr = [...newV, ...this.emojiOptions];
        this.emojiOptions = this.arrRepeat(newArr);
        this.optionArr = newV;
      },
      immediate: true
    }
  },
  created() {
    this.emojiList('');
  },
  mounted() {
    const that = this;
    const SELECTWRAP_DOM = document.querySelector('.related-order-item .el-select-dropdown__wrap');
    if (SELECTWRAP_DOM) {
      SELECTWRAP_DOM.addEventListener('scroll', function() {
        const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
        if (CONDITION) {
          that.emojiLoadMore();
        }
      });
    }
    window.remoteRequest('.related-order-item', this.emojiList);
  },
  methods: {
    emojiLoadMore() {
      const emojiOptions = this.emojiOptions;
      const currentPage = this.currentPage;
      const isMax = emojiOptions.length >= this.emojiTotal;
      if (!isMax) {
        this.emojiList(this.emojioName, currentPage + 1);
      }
    },
    async emojiList(query, page = 1) {
      this.emojioName = query;
      try {
        const params = {
          name: query,
          page,
          perPage: 20
        };
        const res = await getRelatedList(params);
        this.currentPage = res.data.page;
        this.emojiTotal = res.data.total;
        if (query) { // 手动搜索后列表数据无需填充，直接赋值
          if (page > 1 && this.emojiOptions) {
            const concatList = this.emojiOptions.concat(res.data.items);
            this.emojiOptions = concatList;
          } else {
            this.emojiOptions = res.data.items;
          }
        } else {
          const newArr = [...this.optionArr, ...res.data.items];
          if (page > 1 && this.emojiOptions) {
            const concatList = this.emojiOptions.concat(res.data.items);
            this.emojiOptions = this.arrRepeat(concatList);
          } else {
            this.emojiOptions = this.arrRepeat(newArr);
          }
        }
      } catch (error) {
        console.log(error);
      }
    },

    // 数组去重
    arrRepeat(data) {
      const hash = {};
      const data2 = data.reduce((preVal, curVal) => {
        if (!hash[curVal.id]) {
          hash[curVal.id] = true;
          preVal.push(curVal);
        }
        return preVal;
      }, []);
      return data2;
    },

    isShowSelect(val) { // 解决手动搜索后再点击输入框后下拉框无法马上显示列表全部数据
      if (val) {
        this.emojiList('');
      }
    },

    formatOption(value) {
      const len = value.length;
      // 选中 增加
      if (len > this.cacheLen) {
        const arr = this.emojiOptions.filter(item => item.id === value[len - 1]);
        this.deleteAttr(arr, ...this.reservedField);
        this.optionArr = [...this.optionArr, ...arr];
      } else {
        // 删除
        this.optionArr = this.optionArr.filter(item => value.includes(item.id));
      }
      this.cacheLen = value.length;
      this.postMessage();
    },
    // 剔除多余字段
    deleteAttr(arr, ...key) {
      arr.forEach(item => {
        Object.keys(item).forEach(e => {
          if (!key.includes(e)) {
            delete item[e];
          }
        });
      });
    },
    postMessage() {
      try {
        const params = {
          emojiIds: this.relatedIds,
          relatedEmojiOptions: this.optionArr
        };
        this.$emit('postMessage', params);
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.related-order-box {
  & ::v-deep {
    .el-tag--info {
      max-width: 100%;
      // color: #406EFF;
      // background-color: #ecf1ff;
      display: flex;
      align-items: center;
      .el-select__tags-text {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        padding-right: 3px;
      }
      .el-tag__close {
        flex-shrink: 0;
        right: 0;
        top: 1px;
      }
    }
  }
}
</style>
<style lang="scss">
.related-order-item {
  .el-select-dropdown__item {
    font-size: 12px!important;
    .selected {
      font-size: 12px!important;
    }
  }
}
</style>
